package com.azt.front.action.company;

import com.azt.api.enums.RoleTypeEnum;
import com.azt.api.exception.CompanyValidateException;
import com.azt.api.pojo.*;
import com.azt.api.service.*;
import com.azt.front.permission.RequireUser;
import com.azt.front.utils.ContextUtil;
import com.azt.model.AjaxJson;
import com.azt.utils.BeanUtils;
import com.azt.utils.CommonUtil;
import com.xiaoleilu.hutool.util.CollectionUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * @ClassName CompanyAction
 * @Description 企业相关功能控制类
 * @author Snowler
 * @Date 2016年8月17日 下午1:56:16
 * @version 1.0.0
 */
@Controller
@RequestMapping("/company")
public class CompanyAction {

	public static org.slf4j.Logger loggerError = LoggerFactory.getLogger("paError");



	@Autowired
	private UserService us;

	@Autowired
	private CompanyService cs;

	@Autowired
	private DictionaryService ds;

	@Autowired
	private ProCategoryService ps;


	@Autowired
	private CompanyApplifieldService cafs;

	@Autowired
	private MsgConfigService mcfs;

	@Autowired
	private AreaService as;

	/**
	 * @Description 企业资料页面
	 * @return
	 */
	@RequireUser
	@RequestMapping("/info")
	public String companyInfo(HttpServletRequest request , HttpServletResponse response , Model model){
		User u = ContextUtil.getUser();
		Integer per = 0;
		if(u.getCompanyId() != null){
			per += 25;
			u.setCompany(cs.showComDetails(u.getCompanyId().toString()));
			List<Dictionary> applifield = ds.getDictionByParentCode(CommonUtil.APPLIFIELD);//应用领域数据
			model.addAttribute("applifield", applifield);
			List<Category> cats = ps.findTopCategory();//经营系统
			model.addAttribute("cats", cats);
			if(CollectionUtil.isNotEmpty(u.getCompany().getCompanyBanks()))per += 25;
			if(CollectionUtil.isNotEmpty(u.getCompany().getCompanyAssets()))per += 20;
			if(ContextUtil.getCurrentRoleType() != null && ContextUtil.getCurrentRoleType().compareTo(RoleTypeEnum.PROVIDER.getValue()) == 0){
				List<Area> provinces = as.getAreaByParentId(1);//省份
				model.addAttribute("provinces", provinces);
				if(CollectionUtil.isNotEmpty(u.getCompany().getCompanyApplifields()))per += 10;
				if(CollectionUtil.isNotEmpty(u.getCompany().getCompanyCategorys()))per += 10;
				if(CollectionUtil.isNotEmpty(u.getCompany().getCompanyBusinesses()))per += 10;
			}else{
				if(CollectionUtil.isNotEmpty(u.getCompany().getCompanyApplifields()))per += 15;
				if(CollectionUtil.isNotEmpty(u.getCompany().getCompanyCategorys()))per += 15;
			}
		}
		model.addAttribute("per", per);
		model.addAttribute("user", u);

		return "company/info";
	}

	/**
	 * @Description 基本信息的保存和维护方法
	 * @param request
	 * @param response
	 * @param model
	 * @param company
	 * @return
	 */
	@RequireUser
	@ResponseBody
	@RequestMapping( value = "/saveBaseInfo" , method = RequestMethod.POST)
	public AjaxJson baseInfo(HttpServletRequest request , HttpServletResponse response , Model model , Company company){
		if(company != null){
			AjaxJson success = AjaxJson.success();
			boolean needCheck = true;
			try{
				if(company.getId() != null){//编辑
					Company old = cs.getCompanyById(company.getId());
					companyValidate(company , old);
					old.setCompanyInfo(cs.getCompanyInfoByCompanyId(old.getId()));
					needCheck = checkCompanyChanges(old, company);//是否需要审核 如果只修改税号或者企业简介则不需要审核
					BeanUtils.copyBeanNotNull2Bean(company, old, "companyInfo");
					BeanUtils.copyBeanNotNull2Bean(company.getCompanyInfo(), old.getCompanyInfo());
					boolean blen = false;
					if(needCheck && (old.getAuditState().compareTo(Company.AUDIT_STATE_PASS) == 0 || old.getAuditState().compareTo(Company.AUDIT_STATE_BACK) == 0)){
						old.setAuditState(Company.AUDIT_STATE_EDIT);
						blen = true;
					}
					cs.saveOrUpdateCompany(old , null , blen);
				}else{
					companyValidate(company , null);
					company.setRegistertime(new Date());
					company.setCreatetime(new Date());
					company.setAuditState(Company.AUDIT_STATE_INIT);
					company.setRemoved(Company.REMOVED_NO);
					company.setIfSetRole(Company.INIT_STATE);
					company.setFirstPass(Company.FISRT_PASS);
					//company.setIfAuthen(Company.INIT_STATE);
                    company.setIfSelf(0);
                    company.getCompanyInfo().setCompany(company);
					cs.saveOrUpdateCompany(company , ContextUtil.getUser().getId() , true);

					//重新设置session中用户的信息(完整信息，包含公司以及角色信息)  by shangwq  2016.10.21
					ContextUtil.setUser(us.getFullUserById(ContextUtil.getUserId()));
				}
			}catch(CompanyValidateException cve){
				return AjaxJson.error(cve.getErrorCode());
			}catch(Exception e){
				e.printStackTrace();
				return AjaxJson.error("企业资料保存失败，请检查信息是否填写有误，错误原因："+e.getMessage());
			}
			success.setObj(needCheck);
			return success;
		}
		return AjaxJson.error("抱歉，企业数据不存在");
	}

	/*
	*
	* 判断编辑企业的差异  以确定是否需要审核  如果只修改税号和企业简介 则不需要审核
	* */
	private boolean checkCompanyChanges(Company oldC, Company newC) throws Exception {

		boolean res = false;

		if (!oldC.getCompanyName().equals(newC.getCompanyName())) {
			res = true;
		}

		if (oldC.getCompanyInfo() != null && newC.getCompanyInfo() != null) {
			CompanyInfo oldInfo = oldC.getCompanyInfo();
			CompanyInfo newInfo = newC.getCompanyInfo();
			if (oldInfo.getRegProvince() == null ||!oldInfo.getRegProvince().equals(newInfo.getRegProvince()) ||
					oldInfo.getRegCity() == null || !oldInfo.getRegCity().equals(newInfo.getRegCity()) ||
					oldInfo.getRegArea() == null ||!oldInfo.getRegArea().equals(newInfo.getRegArea()) ||
					oldInfo.getRegAddress() == null ||!oldInfo.getRegAddress().equals(newInfo.getRegAddress()) ||
					oldInfo.getBusinessProvince() == null ||!oldInfo.getBusinessProvince().equals(newInfo.getBusinessProvince()) ||
					oldInfo.getBusinessCity() == null ||!oldInfo.getBusinessCity().equals(newInfo.getBusinessCity()) ||
					oldInfo.getBusinessArea() == null ||!oldInfo.getBusinessArea().equals(newInfo.getBusinessArea()) ||
					oldInfo.getBusinessAddress() == null ||!oldInfo.getBusinessAddress().equals(newInfo.getBusinessAddress()) ||
					oldInfo.getLegalperson() == null ||!oldInfo.getLegalperson().equals(newInfo.getLegalperson()) ||
					oldInfo.getRegistercapital() == null ||oldInfo.getRegistercapital().compareTo(newInfo.getRegistercapital()) != 0 ||
					oldInfo.getBusinessLicense() == null ||!oldInfo.getBusinessLicense().equals(newInfo.getBusinessLicense()) ||
					oldInfo.getCurrency() == null ||oldInfo.getCurrency().compareTo(newInfo.getCurrency()) != 0 ||
					((oldInfo.getAuthCertify() == null) || !oldInfo.getAuthCertify().equals(newInfo.getAuthCertify()))) {
					res = true;
			}
		}

		return res;
	}


	@RequireUser
	@ResponseBody
	@RequestMapping( value = "/savelogo" , method = RequestMethod.POST)
	public AjaxJson savelogo(String logoUrl , Integer companyId){

		if(companyId != null && StrUtil.isNotBlank(logoUrl)){

			try {
				cs.changeLogo(logoUrl , companyId);
				return AjaxJson.success();
			}catch (Exception e){
				e.printStackTrace();
				return AjaxJson.error(e.getMessage());
			}

		}
		return  AjaxJson.error("logo修改失败，数据存在问题，请稍后再试");
	}


	/**
	 * @Description 企业资料验证 
	 * @param company
	 * @param old
	 */
	private void companyValidate(Company company , Company old) throws Exception{
		String errorCode = "";
		if(StringUtils.isBlank(company.getCompanyName())) errorCode += "公司名称不能为空\r\n";
		if(!checkCompanyName(company.getCompanyName() , old == null ? null : old.getCompanyName())) errorCode += "公司名称已存在，不能重复\r\n";
		if(company.getIsprovider() == 0 && company.getIspurchaser() == 0) errorCode  += "请选择身份\r\n";
		if(company.getIsprovider() == 1 && company.getProviderMode() == null)errorCode += "供应商请选择经营模式\r\n";
		if(company.getCompanyInfo() == null)errorCode += "基本信息实体不存在\r\n";
		if(company.getCompanyInfo().getRegProvince() == null)errorCode += "请选择注册地址的省份\r\n";
//		if(!CommonUtil.specialArea.contains(company.getCompanyInfo().getRegProvinceArea().getName()) && company.getCompanyInfo().getRegCity() == null)errorCode += "请选择注册地址的城市\r\n";
//		if(!CommonUtil.specialArea.contains(company.getCompanyInfo().getRegProvinceArea().getName()) && company.getCompanyInfo().getRegArea() == null)errorCode += "请选择注册地址的区县\r\n";
		if(StringUtils.isBlank(company.getCompanyInfo().getRegAddress()))errorCode += "请填写注册地址的具体地址\r\n";
		if(company.getCompanyInfo().getBusinessProvince() == null)errorCode += "请选择经营地址的省份\r\n";
//		if(!CommonUtil.specialArea.contains(company.getCompanyInfo().getBusinessProvinceArea().getName()) && company.getCompanyInfo().getBusinessCity() == null)errorCode += "请选择经营地址的城市\r\n";
//		if(!CommonUtil.specialArea.contains(company.getCompanyInfo().getBusinessProvinceArea().getName()) && company.getCompanyInfo().getBusinessArea() == null)errorCode += "请选择经营地址的区县\r\n";
		if(StringUtils.isBlank(company.getCompanyInfo().getBusinessAddress()))errorCode += "请填写经营地址的具体地址\r\n";
		if(company.getCompanyInfo().getRegistercapital() == null)errorCode += "请填写注册资本\r\n";
		if(StringUtils.isBlank(company.getCompanyInfo().getLegalperson()))errorCode += "请填写法人代表\r\n";
//		if(StringUtils.isBlank(company.getCompanyInfo().getBusinessLicense()))errorCode += "请上传营业执照\r\n";
		if(StringUtils.isNotBlank(errorCode)) throw new CompanyValidateException(errorCode);
	}

	@RequestMapping(value = "/checkCompanyName")
	@ResponseBody
	@RequireUser
	public AjaxJson checkCompanyName(Integer companyId , String newName){
		if(companyId != null){
			return checkCompanyName(newName ,  cs.getCompanyById(companyId).getCompanyName()) ? AjaxJson.success() : AjaxJson.error("公司名称已存在，不能重复");
		}else{
			return checkCompanyName(newName , null) ? AjaxJson.success() : AjaxJson.error("公司名称已存在，不能重复");
		}
	}
	
	
	
	/**
	 * @Description 检查企业名称是否重复
	 * @param newName
	 * @param oldName
	 */
	private boolean checkCompanyName(String newName , String oldName){
		if(StringUtils.isNotBlank(oldName)){
			if(oldName.equals(newName)) return true;
		}
		return cs.getCompanyByName(newName) == null ? true : false;
	}
	
	/**
	 * 保存和维护应用领域内容请求
	 * @param company
	 * @return
	 */
	@RequestMapping(value = "/saveField" )
	@ResponseBody
	public AjaxJson saveField(@RequestBody Company company){
		try{
			cafs.saveOrUpdateFields(company);
		}catch(Exception e){
			e.printStackTrace();
			return AjaxJson.error(e.getMessage());
		}
		return AjaxJson.success();
	}


	@RequestMapping(value = "/changeDefaultBank" )
	@ResponseBody
	public AjaxJson changeDefaultBank(Integer bankId){
		try{
			Company company = ContextUtil.getCompany();
			if(company != null && bankId != null){
				cs.changeDefaultBank(company.getId() , bankId);
			}else{
				throw new Exception("未登录企业或财务信息记录不存在！");
			}
		}catch(Exception e){
			e.printStackTrace();
			return AjaxJson.error(e.getMessage());
		}
		return AjaxJson.success();
	}


	/**
	 * 加载财务信息弹框请求
	 * @param bankId
	 * @param model
	 * @return
	 */
	@RequestMapping( value = "/loadBankInfo")
	public String loadBankInfo(Integer bankId , Model model){
		if(bankId != null) {
			CompanyBank bank = cs.getComapnyBankById(bankId);
			model.addAttribute("bank", bank);
			model.addAttribute("bankCodes" , bank.getBankCode() != null ? cs.getOpenBank(bank.getCityArea().getCode(), bank.getBankCode()) : cs.findOpenBankByName(bank.getCityArea().getCode() , bank.getBankName()));
		}
		List<Dictionary> banks = ds.getDictionByParentCode(CommonUtil.BANKS);
		model.addAttribute("banks", banks);
		return "company/bankForm";
	}

	/**
	 * 加载企业资质弹框请求
	 * @param assetId
	 * @param model
	 * @return
	 */
	@RequestMapping( value = "/loadAssetInfo")
	public String loadAssetInfo(Integer assetId , Model model , Integer isPur , Integer isPro){
		if(assetId != null) {
			CompanyAsset asset = cs.getAssetById(assetId);
			model.addAttribute("asset", asset);
		}
		if(isPur != null && isPur == 1){
			List<Dictionary> purAssesTypes = ds.getDictionWithChildByParentCode(CommonUtil.PUR_ASSET_TYPE);
			model.addAttribute("purAssesTypes", purAssesTypes);
		}
		if(isPro != null && isPro == 1){
			List<Dictionary> proAssesTypes = ds.getDictionWithChildByParentCode(CommonUtil.PRO_ASSET_TYPE);
			model.addAttribute("proAssesTypes", proAssesTypes);
		}
		return "company/assetForm";
	}

	/**
	 * 删除财务信息
	 * @param bankId
	 * @return
	 */
	@RequestMapping( value = "/delBankInfo")
	@ResponseBody
	public AjaxJson delBankInfo(Integer bankId){
		if(bankId != null){
			try {
				cs.delBankInfo(bankId);
			}catch (Exception e){
				return AjaxJson.error(e.getMessage());
			}

		}else{
			return AjaxJson.error("银行信息不存在错误");
		}

		return AjaxJson.success();
	}

	/**
	 * 删除企业资质
	 * @param assetId
	 * @return
	 */
	@RequestMapping( value = "/delAsset")
	@ResponseBody
	public AjaxJson delAsset(Integer assetId){
		if(assetId != null){
			try {
				cs.delAsset(assetId);
			}catch (Exception e){
				return AjaxJson.error(e.getMessage());
			}

		}else{
			return AjaxJson.error("企业资质不存在错误");
		}

		return AjaxJson.success();
	}


	/**
	 * 保存财务信息
	 * @param bank
	 * @return
	 */
	@ResponseBody
	@RequestMapping( value = "/saveBank")
	public AjaxJson saveBankInfo(CompanyBank bank){
		try{
			if(bank != null && bank.getCompanyId() != null){
				Integer count = cs.getBankCount(bank.getCompanyId());
				if(count == 0)bank.setIfDefault(CompanyBank.IS_DEFAULT);
				if(bank.getIfDefault() == null)bank.setIfDefault(CompanyBank.IS_NO_DEFAULT);
				boolean blen = false;
				Company company = cs.getCompanyById(bank.getCompanyId());
				String companyName = company.getCompanyName();
				if(company.getAuditState().compareTo(Company.AUDIT_STATE_PASS) == 0 || company.getAuditState().compareTo(Company.AUDIT_STATE_BACK) == 0){
					blen = true;
				}
				cs.saveOrUpdateBank(bank , blen , companyName);
			}
			else return AjaxJson.error("银行信息不存在");
		}catch(Exception e){
			e.printStackTrace();
			return AjaxJson.error(e.getMessage());
		}
		return AjaxJson.success();
	}

	/**
	 * @Description 保存企业资质
	 * @param asset
	 * @return
	 */
	@ResponseBody
	@RequestMapping( value = "/saveAsset")
	public AjaxJson saveAsset(CompanyAsset asset){
		try{
			if(asset != null && asset.getCompanyId() != null){
				cs.saveOrUpdateAsset(asset);
			}
			else return AjaxJson.error("银行信息不存在");
		}catch(Exception e){
			e.printStackTrace();
			return AjaxJson.error(e.getMessage());
		}
		return AjaxJson.success();
	}
}
